# ui/main_window.py
from PySide2.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QComboBox, QCheckBox, QPushButton, QTextEdit, 
    QGroupBox, QGridLayout, QScrollArea, QMessageBox, QLineEdit,
    QFileDialog, QTabWidget, QProgressDialog
)
from config.constants import *
from PySide2.QtCore import Qt, QThread, Signal
from config.constants import PROVINCE_CITY, OPERATOR_PREFIX, ADCODE_MAP
from core.api_client import APIClient
from core.phone_processor import PhoneProcessor
import pandas as pd
import os
from PySide2 import QtGui

class PhoneNumberGenerator(QMainWindow):
    def __init__(self, api_base_url, api_token):
        super().__init__()
        self.setWindowTitle("小靓号 - 靓号挑选工具 (仅供个人使用，禁止非法用途)")
        self.resize(900, 700)
        self.generated_numbers = []
        self.history = []
        self.current_page = 1  # 当前页码
        self.page_size = 50  # 每页显示数量
        
        # 初始化API客户端和处理器
        self.api_client = APIClient(api_base_url, api_token)
        self.processor = PhoneProcessor()
        
        self.init_ui()

    def init_ui(self):
        """初始化用户界面"""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        
        # 创建标签页
        self.tabs = QTabWidget()
        
        # 主界面标签页
        main_tab = QWidget()
        main_tab_layout = QVBoxLayout(main_tab)
        
        # 配置区域
        config_group = QGroupBox("查询配置")
        config_layout = QGridLayout(config_group)
        
        # 省份城市选择
        config_layout.addWidget(QLabel("省份："), 0, 0)
        self.province_box = QComboBox()
        self.province_box.addItems(PROVINCE_CITY.keys())
        config_layout.addWidget(self.province_box, 0, 1)
        
        config_layout.addWidget(QLabel("城市："), 1, 0)
        self.city_box = QComboBox()
        self.update_city_list()
        self.province_box.currentTextChanged.connect(self.update_city_list)
        config_layout.addWidget(self.city_box, 1, 1)
        
        # 运营商选择 - 修改为电话号码前三位的选择
        config_layout.addWidget(QLabel("号段选择："), 2, 0)
        
        # 创建滚动区域来容纳所有号段选择
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_widget = QWidget()
        scroll_layout = QVBoxLayout(scroll_widget)
        
        # 创建号段分组
        self.prefix_checkboxes = {}
        self.operator_select_all = {}  # 存储各运营商的全选按钮
        
        for operator, prefixes in OPERATOR_PREFIX.items():
            group_box = QGroupBox(operator)
            group_layout = QGridLayout(group_box)
            
            # 添加全选按钮
            select_all = QCheckBox("全选")
            self.operator_select_all[operator] = select_all
            select_all.stateChanged.connect(lambda state, op=operator: self.toggle_operator_selection(op, state))
            group_layout.addWidget(select_all, 0, 0, 1, 6)  # 横跨6列
            
            row, col = 1, 0  # 从第1行开始
            for prefix in prefixes:
                cb = QCheckBox(prefix)
                self.prefix_checkboxes[prefix] = cb
                group_layout.addWidget(cb, row, col)
                col += 1
                if col >= 6:  # 每行6个
                    col = 0
                    row += 1
            
            scroll_layout.addWidget(group_box)
        
        scroll_widget.setLayout(scroll_layout)
        scroll_area.setWidget(scroll_widget)
        config_layout.addWidget(scroll_area, 2, 1)
        
        # 号码格式选择
        config_layout.addWidget(QLabel("末尾四位格式："), 3, 0)
        self.pattern_checkboxes = {}
        pattern_layout = QHBoxLayout()
        
        # 更新为用户提供的格式
        new_patterns = ["全选", "AAAA", "AAA", "AAAB", "AABA", "AABB", "AABC", "ABAA", "ABAB", "ABAC", "ABBA", "ABBC", "ABCA", "ABCB", "ABCC", "ABCD"]
        for pattern in new_patterns:
            cb = QCheckBox(pattern)
            self.pattern_checkboxes[pattern] = cb
            pattern_layout.addWidget(cb)
        
        config_layout.addLayout(pattern_layout, 3, 1)
        
        main_tab_layout.addWidget(config_group)
        
        # 按钮区域
        btn_layout = QHBoxLayout()
        
        self.generate_btn = QPushButton("生成靓号")
        self.generate_btn.clicked.connect(self.generate_mask_numbers)
        btn_layout.addWidget(self.generate_btn)
        
        self.export_phone_btn = QPushButton("导出手机格式")
        self.export_phone_btn.clicked.connect(self.export_phone_format)
        self.export_phone_btn.setEnabled(False)
        btn_layout.addWidget(self.export_phone_btn)
        
        self.export_excel_btn = QPushButton("导出Excel")
        self.export_excel_btn.clicked.connect(self.export_excel)
        self.export_excel_btn.setEnabled(False)
        btn_layout.addWidget(self.export_excel_btn)
        
        main_tab_layout.addLayout(btn_layout)
        
        # 结果显示区域
        self.result_edit = QTextEdit()
        self.result_edit.setReadOnly(True)
        main_tab_layout.addWidget(self.result_edit)
        
        # 分页控件
        self.pagination_layout = QHBoxLayout()
        
        # 首页按钮
        self.first_btn = QPushButton("首页")
        self.first_btn.clicked.connect(self.first_page)
        self.first_btn.setEnabled(False)
        self.pagination_layout.addWidget(self.first_btn)
        
        # 上一页按钮
        self.prev_btn = QPushButton("上一页")
        self.prev_btn.clicked.connect(self.prev_page)
        self.prev_btn.setEnabled(False)
        self.pagination_layout.addWidget(self.prev_btn)
        
        # 页码按钮 (只显示4个)
        self.page_labels = []
        for i in range(1, 5):
            page_btn = QPushButton(str(i))
            page_btn.clicked.connect(lambda *args, page=i: self.go_to_page(page))
            if i == 1:
                page_btn.setStyleSheet("background-color: blue; color: white;")
            self.page_labels.append(page_btn)
            self.pagination_layout.addWidget(page_btn)
        
        # 下一页按钮
        self.next_btn = QPushButton("下一页")
        self.next_btn.clicked.connect(self.next_page)
        self.next_btn.setEnabled(False)
        self.pagination_layout.addWidget(self.next_btn)
        
        # 尾页按钮
        self.last_btn = QPushButton("尾页")
        self.last_btn.clicked.connect(self.last_page)
        self.last_btn.setEnabled(False)
        self.pagination_layout.addWidget(self.last_btn)
        
        main_tab_layout.addLayout(self.pagination_layout)
        
        # 历史记录标签页
        history_tab = QWidget()
        history_layout = QVBoxLayout(history_tab)
        self.history_edit = QTextEdit()
        self.history_edit.setReadOnly(True)
        history_layout.addWidget(self.history_edit)
        
        # 添加标签页到标签控件
        self.tabs.addTab(main_tab, "号码生成")
        self.tabs.addTab(history_tab, "历史记录")
        
        main_layout.addWidget(self.tabs)
        
    def toggle_operator_selection(self, operator, state):
        """切换运营商号段的全选状态"""
        prefixes = OPERATOR_PREFIX[operator]
        for prefix in prefixes:
            if prefix in self.prefix_checkboxes:
                self.prefix_checkboxes[prefix].setChecked(state == Qt.Checked)
        
    def update_city_list(self):
        """更新城市列表"""
        province = self.province_box.currentText()
        self.city_box.clear()
        self.city_box.addItems(PROVINCE_CITY.get(province, []))
        
    def generate_mask_numbers(self):
        """生成靓号"""
        selected_city = self.city_box.currentText()
        # 获取选中的号段
        selected_prefixes = [prefix for prefix, cb in self.prefix_checkboxes.items() if cb.isChecked()]
        selected_patterns = [pat for pat, cb in self.pattern_checkboxes.items() if cb.isChecked() and pat != "全选"]
        
        if not all([selected_city, selected_prefixes, selected_patterns]):
            QMessageBox.warning(self, "参数缺失", "请选择完整的城市、号段和号码格式")
            return
        
        # 获取城市编码
        city_adcode = ADCODE_MAP.get(selected_city, "")
        if not city_adcode:
            QMessageBox.warning(self, "城市编码缺失", f"未找到{selected_city}的编码，请补充配置")
            return
            
        # 构建运营商前缀
        prefixes = ",".join(selected_prefixes)
        masks = ",".join(selected_patterns)
        
        # 调用API
        response = self.api_client.query_mask_code(city_adcode, prefixes, masks)
        print(f"response status: {response.status_code}")
        
        # 处理结果
        if response.status_code == 200:
            json = response.json()
            print(f"response status: {response.status_code}")
            self.generated_numbers = self.processor.generate_phone_numbers(
            json.get("prefixInfo", []), 
            json.get("suffix", []))
            self.display_results()
            self.save_history(f"查询靓号 - {selected_city} - {', '.join(selected_prefixes)} - {', '.join(selected_patterns)}")
            self.export_excel_btn.setEnabled(True)
            self.export_phone_btn.setEnabled(True)
        else:
            error_msg = json.get("message", "未知错误")
            QMessageBox.critical(self, "查询失败", f"API调用失败: {error_msg}")
    
    def display_results(self):
        """显示结果"""
        self.result_edit.clear()
        
        total = len(self.generated_numbers)
        start_idx = (self.current_page - 1) * self.page_size
        end_idx = min(start_idx + self.page_size, total)
        
        for i, num in enumerate(self.generated_numbers[start_idx:end_idx], start_idx + 1):
            self.result_edit.append(f"{i}. {num['city']} | {num['isp']} | {num['phone']} | 格式：{num['pattern']}")
        
        self.result_edit.append(f"\n共生成 {total} 个号码")
        self.result_edit.append(f"当前显示第 {self.current_page} 页，共 {self.get_total_pages()} 页")
        
        # 更新分页按钮状态
        self.first_btn.setEnabled(self.current_page > 1)
        self.prev_btn.setEnabled(self.current_page > 1)
        self.next_btn.setEnabled(self.current_page < self.get_total_pages())
        self.last_btn.setEnabled(self.current_page < self.get_total_pages())
        
        # 动态更新页码按钮
        total_pages = self.get_total_pages()
        
        # 确定页码范围
        if self.current_page <= 2 or total_pages <= 4:
            # 前两页或总页数少于等于4，显示1-4页
            page_range = range(1, min(5, total_pages + 1))
        else:
            # 从当前页-2开始，显示4个页码
            start_page = max(1, self.current_page - 2)
            end_page = min(start_page + 3, total_pages)
            page_range = range(start_page, end_page + 1)
            
            # 如果不足4个页码，向前扩展
            while len(page_range) < 4 and page_range[0] > 1:
                page_range = range(page_range[0] - 1, page_range[-1] + 1)
        
        # 更新页码按钮
        for i, page_btn in enumerate(self.page_labels):
            if i < len(page_range):
                page_num = page_range[i]
                page_btn.setText(str(page_num))
                page_btn.clicked.disconnect()
                page_btn.clicked.connect(lambda *args, page=page_num: self.go_to_page(page))
                
                if page_num == self.current_page:
                    page_btn.setStyleSheet("background-color: blue; color: white;")
                else:
                    page_btn.setStyleSheet("")
                
                page_btn.setEnabled(True)
            else:
                page_btn.setText("")
                page_btn.setEnabled(False)
                page_btn.setStyleSheet("")
    
    def get_total_pages(self):
        """获取总页数"""
        return max(1, (len(self.generated_numbers) + self.page_size - 1) // self.page_size)
    
    def prev_page(self):
        """上一页"""
        if self.current_page > 1:
            self.current_page -= 1
            self.display_results()
    
    def next_page(self):
        """下一页"""
        if self.current_page < self.get_total_pages():
            self.current_page += 1
            self.display_results()
    
    def first_page(self):
        """首页"""
        self.current_page = 1
        self.display_results()
    
    def last_page(self):
        """尾页"""
        self.current_page = self.get_total_pages()
        self.display_results()
    
    def go_to_page(self, page):
        """跳转到指定页"""
        if 1 <= page <= self.get_total_pages():
            self.current_page = page
            self.display_results()
    
    def save_history(self, query_info):
        """保存查询历史"""
        timestamp = pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S")
        history_entry = f"{timestamp} - {query_info} - 共{len(self.generated_numbers)}个号码"
        self.history.append(history_entry)
        self.update_history_display()
    
    def update_history_display(self):
        """更新历史记录显示"""
        self.history_edit.clear()
        for entry in reversed(self.history):
            self.history_edit.append(entry + "\n")
    
    # 导出线程类
    class ExportThread(QThread):
        progress_updated = Signal(int)
        export_completed = Signal(bool, str)
        
        def __init__(self, numbers, file_path):
            super().__init__()
            self.numbers = numbers
            self.file_path = file_path
            
        def run(self):
            try:
                total = len(self.numbers)
                
                if self.file_path.endswith('.xlsx'):
                    df = pd.DataFrame(self.numbers)
                    df.to_excel(self.file_path, index=False, sheet_name="靓号列表")
                    self.progress_updated.emit(100)
                elif self.file_path.endswith('.csv'):
                    df = pd.DataFrame(self.numbers)
                    df.to_csv(self.file_path, index=False, encoding='utf-8-sig')
                    self.progress_updated.emit(100)
                elif self.file_path.endswith('.txt'):
                    with open(self.file_path, 'w', encoding='utf-8') as f:
                        for i, num in enumerate(self.numbers):
                            f.write(f"{num['city']} | {num['isp']} | {num['phone']} | 格式：{num['pattern']}\n")
                            progress = int((i + 1) / total * 100)
                            self.progress_updated.emit(progress)
                elif self.file_path.endswith('.vcf'):
                    with open(self.file_path, 'w', encoding='utf-8') as f:
                        for i, num in enumerate(self.numbers):
                            # 创建vCard格式内容
                            vcard = [
                                'BEGIN:VCARD',
                                'VERSION:3.0',
                                f'N:{num["pattern"]};{num["phone"]};;;',
                                f'FN:{num["phone"]} ({num["pattern"]})',
                                f'TEL;TYPE=CELL:{num["phone"]}',
                                f'NOTE:城市: {num["city"]}, 运营商: {num["isp"]}, 格式: {num["pattern"]}',
                                'END:VCARD'
                            ]
                            f.write('\n'.join(vcard) + '\n\n')
                            progress = int((i + 1) / total * 100)
                            self.progress_updated.emit(progress)
                
                self.export_completed.emit(True, f"已成功导出 {total} 个号码到 {self.file_path}")
            except Exception as e:
                self.export_completed.emit(False, f"导出文件时出错: {str(e)}")
    
    def export_excel(self):
        """导出为Excel格式"""
        if not self.generated_numbers:
            QMessageBox.warning(self, "导出失败", "没有可导出的号码")
            return
            
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存Excel文件", os.path.expanduser("~"), 
            "Excel文件 (*.xlsx)"
        )
        
        if not file_path:
            return
            
        # 确保文件扩展名为.xlsx
        if not file_path.endswith('.xlsx'):
            file_path += '.xlsx'
            
        # 创建进度对话框
        self.progress_dialog = QProgressDialog("正在导出Excel...", None, 0, 100, self)
        self.progress_dialog.setWindowTitle("导出进度")
        self.progress_dialog.setWindowModality(Qt.WindowModal)
        self.progress_dialog.show()
        
        # 创建并启动导出线程
        self.export_thread = self.ExportThread(self.generated_numbers, file_path)
        self.export_thread.progress_updated.connect(self.progress_dialog.setValue)
        self.export_thread.export_completed.connect(self.on_export_completed)
        self.export_thread.start()
        
    def export_phone_format(self):
        """导出为手机通讯录格式(VCF)"""
        if not self.generated_numbers:
            QMessageBox.warning(self, "导出失败", "没有可导出的号码")
            return
            
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存通讯录文件", os.path.expanduser("~"), 
            "通讯录文件 (*.vcf)"
        )
        
        if not file_path:
            return
            
        # 确保文件扩展名为.vcf
        if not file_path.endswith('.vcf'):
            file_path += '.vcf'
            
        # 创建进度对话框
        self.progress_dialog = QProgressDialog("正在导出通讯录...", None, 0, 100, self)
        self.progress_dialog.setWindowTitle("导出进度")
        self.progress_dialog.setWindowModality(Qt.WindowModal)
        self.progress_dialog.show()
        
        # 创建并启动导出线程
        self.export_thread = self.ExportThread(self.generated_numbers, file_path)
        self.export_thread.progress_updated.connect(self.progress_dialog.setValue)
        self.export_thread.export_completed.connect(self.on_export_completed)
        self.export_thread.start()
    
    def update_progress(self, value):
        """更新进度条"""
        self.progress_dialog.setValue(value)
    
    def on_export_completed(self, success, message):
        """处理导出完成事件"""
        self.progress_dialog.close()
        
        if success:
            QMessageBox.information(self, "导出成功", message)
        else:
            QMessageBox.critical(self, "导出失败", message)